﻿using Microsoft.Extensions.Logging;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using WMS.Model;
using WMS.Repository.IRepository;

namespace WMS.Repository
{
    public class RoleRepository : BaseRepository<RoleModel>, IRoleRepository
    {
        public RoleRepository(ISqlSugarClient db, ILogger<RoleRepository> logger) : base(db, logger)
        {
        }

        /// <summary>
        /// 添加角色
        /// </summary>
        public async Task<bool> AddRoleAsync(RoleModel roleModel)
        {
            try
            {
                return await _db.Insertable(roleModel).ExecuteCommandAsync() > 0;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"添加角色失败 - 角色名称: {roleModel?.RoleName}");
                throw;
            }
        }

        /// <summary>
        /// 角色分页模糊查询
        /// </summary>
        public async Task<PageResult<RoleModel>> GetRolePagedListAsync(RoleQueryRequest request)
        {
            try
            {
                var query = _db.Queryable<RoleModel>();

                // 添加模糊查询条件
                if (!string.IsNullOrEmpty(request.RoleName))
                    query = query.Where(u => u.RoleName.Contains(request.RoleName));

                // 精确匹配状态
                if (request.Status.HasValue)
                    query = query.Where(u => u.Status == request.Status.Value);

                // 按创建时间倒序
                query = query.OrderBy(u => u.CreateTime, OrderByType.Desc);

                // 执行分页查询
                RefAsync<int> totalCount = 0;
                var data = await query.ToPageListAsync(request.PageIndex, request.PageSize, totalCount);

                return new PageResult<RoleModel>
                {
                    PageIndex = request.PageIndex,
                    PageSize = request.PageSize,
                    TotalCount = totalCount,
                    TotalPages = (int)Math.Ceiling(totalCount / (double)request.PageSize),
                    Data = data
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"角色分页查询失败 - 角色名称: {request.RoleName}, 状态: {request.Status}, 页码: {request.PageIndex}, 页大小: {request.PageSize}");
                throw;
            }
        }

        /// <summary>
        /// 获取角色信息
        /// </summary>
        public async Task<RoleModel> GetRoleNameAsync(string roleName)
        {
            try
            {
                return await _db.Queryable<RoleModel>().Where(x => x.RoleName == roleName).FirstAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"查询角色失败 - 角色名称: {roleName}");
                throw;
            }
        }
    }
}